"use client"

import { useState, useEffect } from "react"
import { useParams } from "react-router-dom"
import "./OtherProfilePage.css"

function OtherProfile() {
  const { userId: targetUserId } = useParams() // 从路由获取目标用户ID
  const currentUserId = localStorage.getItem("userId") // 当前登录用户ID

  const [activeTab, setActiveTab] = useState("downloads")
  const [torrents, setTorrents] = useState([])
  const [downloads, setDownloads] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(null)

  const [followStats, setFollowStats] = useState({
    followingCount: 0,
    followersCount: 0,
  })
  const [followModal, setFollowModal] = useState({
    isOpen: false,
    type: "", // 'following' or 'followers'
    list: [],
    loading: false,
  })

  // 关注状态
  const [isFollowing, setIsFollowing] = useState(false)
  const [followLoading, setFollowLoading] = useState(false)

  // 用户信息
  const [userProfile, setUserProfile] = useState({
    avatarUrl: "/default_avatar.jpg",
    nickname: "",
    gender: "",
    bio: "介绍一下自己吧...",
    level: "",
    userPoints: "",
    shareRate: "",
    uploadCount: "",
    downloadCount: "",
  })

  const [assessmentStatus, setAssessmentStatus] = useState("未考核")
  const [totalCount, setTotalCount] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(5)
  const [perPage] = useState(10)

  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    const userId = localStorage.getItem("userId")

    if (!token || !userId) {
      console.error("用户未登录")
      return null
    }

    return {
      Authorization: `Bearer ${token}`,
    }
  }

  // 获取目标用户头像
  const fetchUserAvatar = async (userId) => {
    let avatarUrl = "/default_avatar.jpg"

    try {
      if (!targetUserId) throw new Error("用户ID不存在")

      const response = await fetch(`/user/get-avatar?userId=${userId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) throw new Error(`获取头像失败: ${response.status}`)

      const data = await response.json()

      if (data.code === 0 && data.result) {
        avatarUrl = data.msg

        if (avatarUrl) {
          if (avatarUrl.startsWith("data:image/")) {
            // Base64 with prefix
          } else if (avatarUrl.length > 1000) {
            avatarUrl = `data:image/jpeg;base64,${avatarUrl}`
          } else if (!avatarUrl.startsWith("/") && !avatarUrl.startsWith("http")) {
            avatarUrl = `/${avatarUrl}`
          }
        }
      }
    } catch (error) {
      console.error("获取头像错误:", error)
    }

    return avatarUrl
  }

  // 自动调整sizeGB
  const formatSize = (sizeInGB) => {
    const sizeInMB = sizeInGB * 1024
    const sizeInKB = sizeInMB * 1024

    if (sizeInGB >= 1) {
      return `${sizeInGB.toFixed(2)} GB`
    } else if (sizeInMB >= 1) {
      return `${sizeInMB.toFixed(2)} MB`
    } else {
      return `${sizeInKB.toFixed(2)} KB`
    }
  }

  // 获取目标用户信息
  const fetchUserProfile = async () => {
    try {
      const response = await fetch(`/user/level?userId=${targetUserId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取个人信息失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result) {
        const avatarUrl = await fetchUserAvatar(targetUserId)

        const profileData = {
          userId: targetUserId,
          nickname: data.rows.userData.nickname,
          gender: data.rows.userData.sex,
          bio: data.rows.userData.introduction,
          level: data.rows.userData.level,
          userPoints: data.rows.userData.userPoints,
          shareRate: data.rows.userData.shareRate,
          uploadCount: data.rows.userData.uploadCount,
          downloadCount: data.rows.userData.downloadCount,
          avatarUrl: avatarUrl,
        }

        setUserProfile(profileData)
      } else {
        throw new Error(data.msg || "获取个人信息失败")
      }
    } catch (err) {
      console.error("获取个人信息错误:", err)
      setError(err.message)
    }
  }

  // 获取用户上传的种子列表
  const fetchUserTorrents = async () => {
    if (activeTab !== "uploads") return

    setIsLoading(true)
    setError(null)

    try {
      const response = await fetch(`/torrent/getUserTorrents?user_id=${targetUserId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取种子列表失败")
      }

      const data = await response.json()
      console.log("获取种子列表:", data)

      if (data.code === 0 && data.result) {
        setTorrents(data.rows || [])
      } else {
        throw new Error(data.msg || "获取种子列表失败")
      }
    } catch (err) {
      setError(err.message)
      console.error("获取种子列表错误:", err)
    } finally {
      setIsLoading(false)
    }
  }

  // 获取用户下载记录
  const fetchDownloadRecords = async (page = currentPage) => {
    if (activeTab !== "downloads") return

    setIsLoading(true)
    setError(null)

    try {
      const response = await fetch(`/download/records?user_id=${targetUserId}&page=${page}&per_page=${perPage}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取下载列表失败")
      }

      const data = await response.json()
      console.log("获取下载列:", data)

      if (data.code === 0 && data.result) {
        setDownloads(data.rows || [])
        setTotalCount(data.total || 0)
        if (data.total) {
          setTotalPages(Math.ceil(data.total / perPage))
        }
      } else {
        throw new Error(data.msg || "获取下载列表失败")
      }
    } catch (err) {
      setError(err.message)
      console.error("获取下载列表错误:", err)
    } finally {
      setIsLoading(false)
    }
  }

  // 获取考核结果
  const fetchAssessmentStatus = async () => {
    try {
      const response = await fetch(`/user/assessment/latestResult?userId=${targetUserId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取考核结果失败")
      }

      const data = await response.json()
      console.log("考核结果", data)
      if (data.code === 0 && data.rows) {
        setAssessmentStatus(data.rows.assessmentStatus)
      } else {
        throw new Error(data.msg || "获取考核结果失败")
      }
    } catch (err) {
      console.error("获取考核结果错误:", err)
    }
  }

  // 获取关注列表
  const fetchFollowingList = async () => {
    try {
      const response = await fetch(`/follow/following?user_id=${targetUserId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取关注列表失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result) {
        setFollowStats((prev) => ({
          ...prev,
          followingCount: data.rows.following_count || 0,
        }))
        return data.rows.following_list || []
      }
      return []
    } catch (err) {
      console.error("获取关注列表错误:", err)
      return []
    }
  }

  // 获取用户详细信息
  const fetchUserDetails = async (userId) => {
    try {
      const response = await fetch(`/user/level?userId=${userId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取用户信息失败")
      }
      const avatarUrl = await fetchUserAvatar(userId)
      const data = await response.json()
      if (data.code === 0 && data.result) {
        return {
          userId: userId,
          nickname: data.rows.userData.nickname,
          level: data.rows.userData.level,
          userPoints: data.rows.userData.userPoints,
          avatarUrl: avatarUrl,
          introduction: data.rows.userData.introduction,
        }
      }
      return null
    } catch (err) {
      console.error(`获取用户${userId}信息错误:`, err)
      return null
    }
  }

  // 批量获取用户详细信息
  const fetchUsersDetails = async (userIds) => {
    const userDetails = []

    // 限制并发请求数量
    const batchSize = 5
    for (let i = 0; i < userIds.length; i += batchSize) {
      const batch = userIds.slice(i, i + batchSize)
      const batchPromises = batch.map((userId) => fetchUserDetails(userId))
      const batchResults = await Promise.all(batchPromises)
      userDetails.push(...batchResults.filter((detail) => detail !== null))

      // 添加小延迟避免请求过于频繁
      if (i + batchSize < userIds.length) {
        await new Promise((resolve) => setTimeout(resolve, 100))
      }
    }

    return userDetails
  }

  // 获取粉丝列表
  const fetchFollowersList = async () => {
    try {
      const response = await fetch(`/follow/followers?user_id=${targetUserId}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取粉丝列表失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result) {
        setFollowStats((prev) => ({
          ...prev,
          followersCount: data.rows.follower_count || 0,
        }))
        return data.rows.follower_list || []
      }
      return []
    } catch (err) {
      console.error("获取粉丝列表错误:", err)
      return []
    }
  }

  // 检查是否已关注该用户
  const checkFollowStatus = async () => {
    try {
      const response = await fetch(`/follow/check?follower_id=${currentUserId}&followed_id=${targetUserId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("检查关注状态失败")
      }

      const data = await response.json()
      if (data.code === 0) {
        setIsFollowing(data.rows["is_following"] || false)
      }
    } catch (err) {
      console.error("检查关注状态错误:", err)
    }
  }

  // 关注/取消关注用户
  const handleFollowToggle = async () => {
    if (followLoading) return

    setFollowLoading(true)
    try {
      const endpoint = isFollowing
        ? `/follow/unfollow?follower_id=${currentUserId}&followed_id=${targetUserId}`
        : `/follow/follow?follower_id=${currentUserId}&followed_id=${targetUserId}`

      const response = await fetch(endpoint, {
        method: "POST",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error(isFollowing ? "取消关注失败" : "关注失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result) {
        setIsFollowing(!isFollowing)
        // 重新获取关注数据
        fetchFollowersList()
        fetchFollowingList()
      } else {
        throw new Error(data.msg || (isFollowing ? "取消关注失败" : "关注失败"))
      }
    } catch (err) {
      console.error("关注操作错误:", err)
      alert(err.message)
    } finally {
      setFollowLoading(false)
    }
  }

  // 打开关注/粉丝列表模态框
  const handleOpenFollowModal = async (type) => {
    setFollowModal({
      isOpen: true,
      type,
      list: [],
      loading: true,
    })

    let userIds = []
    if (type === "following") {
      const followingData = await fetchFollowingList()
      userIds = followingData
    } else if (type === "followers") {
      const followersData = await fetchFollowersList()
      userIds = followersData
    }

    // 获取用户详细信息
    const userDetails = await fetchUsersDetails(userIds)

    setFollowModal((prev) => ({
      ...prev,
      list: userDetails,
      loading: false,
    }))
  }

  // 关闭关注/粉丝列表模态框
  const handleCloseFollowModal = () => {
    setFollowModal({
      isOpen: false,
      type: "",
      list: [],
      loading: false,
    })
  }

  useEffect(() => {
    if (!targetUserId) {
      setError("用户ID无效")
      return
    }

    fetchAssessmentStatus()
    fetchUserProfile()
    fetchFollowingList()
    fetchFollowersList()

    // 如果不是查看自己的资料，检查关注状态
    if (currentUserId && targetUserId !== currentUserId) {
      checkFollowStatus()
    }
  }, [targetUserId])

  useEffect(() => {
    if (activeTab === "uploads") {
      fetchUserTorrents()
    } else if (activeTab === "downloads") {
      fetchDownloadRecords(1)
      setCurrentPage(1)
    }
  }, [activeTab])

  const handlePageChange = (page) => {
    setCurrentPage(page)
    fetchDownloadRecords(page)
  }

  const renderPagination = () => {
    const pages = []

    const startPage = Math.max(1, currentPage - 2)
    const endPage = Math.min(totalPages, currentPage + 2)

    if (startPage > 1) {
      pages.push(
        <button key="first" className="page-button" onClick={() => handlePageChange(1)}>
          首页
        </button>,
      )
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`page-button ${i === currentPage ? "active" : ""}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>,
      )
    }

    if (endPage < totalPages) {
      pages.push(
        <button key="last" className="page-button" onClick={() => handlePageChange(totalPages)}>
          末页
        </button>,
      )
    }

    return pages
  }

  // 判断是否是查看自己的资料
  const isOwnProfile = currentUserId === targetUserId

  return (
    <div className="other-profile-page">
      <div className="other-profile-container">
        <div className="other-profile-grid">
          <div className="other-profile-sidebar">
            <div className="user-profile">
              <div className="user-avatar-container">
                <img
                  src={userProfile.avatarUrl || "/default_avatar.jpg"}
                  alt="用户头像"
                  className="user-avatar"
                  onError={(e) => {
                    console.log("头像加载失败，使用默认头像")
                    e.target.src = "/default_avatar.jpg"
                  }}
                />
              </div>
              <h2 className="user-name">{userProfile.nickname}</h2>
              <p className="user-gender">
                {userProfile.gender === "male" ? "男" : userProfile.gender === "female" ? "女" : userProfile.gender}
              </p>
              <p className="user-bio">{userProfile.bio}</p>

              <div className="user-stats">
                <div className="stat-row">
                  <div className="stat-item">
                    <span className="stat-label">积分:</span>
                    <span className="stat-value">{userProfile.userPoints}</span>
                  </div>
                  <div className="stat-item">
                    <span className="stat-label">等级:</span>
                    <span className="stat-value">{userProfile.level}级</span>
                  </div>
                </div>

                <div className="stat-row">
                  <div className="stat-item">
                    <span className="stat-label">上传/下载量:</span>
                    <span className="stat-value">
                      {userProfile.uploadCount}GB/{userProfile.downloadCount}GB
                    </span>
                  </div>
                </div>

                <div className="stat-row">
                  <div className="stat-item">
                    <span className="stat-label">分享率:</span>
                    <span className="stat-value">{Number(userProfile.shareRate).toFixed(2)}</span>
                  </div>
                  <div className="stat-item">
                    <span className="stat-label">考核:</span>
                    <span className="stat-value">{assessmentStatus}</span>
                  </div>
                </div>

                <div className="stat-row">
                  <div className="stat-item follow-stat-item" onClick={() => handleOpenFollowModal("following")}>
                    <span className="stat-label">关注:</span>
                    <span className="stat-value clickable">{followStats.followingCount}</span>
                  </div>
                  <div className="stat-item follow-stat-item" onClick={() => handleOpenFollowModal("followers")}>
                    <span className="stat-label">粉丝:</span>
                    <span className="stat-value clickable">{followStats.followersCount}</span>
                  </div>
                </div>
              </div>

              {/* 只有在查看他人资料时显示关注按钮 */}
              {!isOwnProfile && (
                <div className="follow-actions">
                  <button
                    className={`follow-button ${isFollowing ? "following" : "not-following"}`}
                    onClick={handleFollowToggle}
                    disabled={followLoading}
                  >
                    {followLoading ? "处理中..." : isFollowing ? "已关注" : "关注"}
                  </button>
                </div>
              )}
            </div>
          </div>

          <div className="other-profile-content">
            <div className="other-profile-tabs">
              <button
                className={`tab-button ${activeTab === "downloads" ? "active" : ""}`}
                onClick={() => setActiveTab("downloads")}
              >
                下载视频
              </button>
              <button
                className={`tab-button ${activeTab === "uploads" ? "active" : ""}`}
                onClick={() => setActiveTab("uploads")}
              >
                上传视频
              </button>
            </div>

            <div className="tab-content">
              {activeTab === "downloads" && (
                <div className="downloads-tab">
                  {isLoading ? (
                    <div className="loading-state">加载中...</div>
                  ) : error ? (
                    <div className="error-state">
                      <p>出错了: {error}</p>
                      <button onClick={() => fetchDownloadRecords(currentPage)} className="retry-button">
                        重试
                      </button>
                    </div>
                  ) : downloads.length > 0 ? (
                    <>
                      <p className="collection-count">共有 {totalCount} 个下载记录</p>

                      <div className="downloads-table">
                        <table>
                          <thead>
                            <tr>
                              <th>名称</th>
                              <th>下载时间</th>
                              <th>大小</th>
                            </tr>
                          </thead>
                          <tbody>
                            {downloads.map((download) => (
                              <tr key={download.downloadId}>
                                <td className="download-title-cell">
                                  <div className="download-title-with-image">
                                    <span>{download.torrentTitle}</span>
                                  </div>
                                </td>
                                <td>{new Date(download.downloadTime).toLocaleString()}</td>
                                <td>{formatSize(download.downloadSize)}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>

                      <div className="pagination">{renderPagination()}</div>
                    </>
                  ) : (
                    <p>暂无下载记录</p>
                  )}
                </div>
              )}

              {activeTab === "uploads" && (
                <div className="uploads-tab">
                  {isLoading ? (
                    <div className="loading-state">加载中...</div>
                  ) : error ? (
                    <div className="error-state">
                      <p>出错了: {error}</p>
                      <button onClick={fetchUserTorrents} className="retry-button">
                        重试
                      </button>
                    </div>
                  ) : torrents.length > 0 ? (
                    <>
                      <p className="collection-count">共上传了 {torrents.length} 个种子</p>
                      <div className="downloads-table">
                        <table>
                          <thead>
                            <tr>
                              <th>名称</th>
                              <th>上传时间</th>
                              <th>类别</th>
                            </tr>
                          </thead>
                          <tbody>
                            {torrents.map((torrent) => (
                              <tr key={torrent.torrentId}>
                                <td className="download-title-cell">
                                  <div className="download-title-with-image">
                                    <span>{torrent.title}</span>
                                  </div>
                                </td>
                                <td>{new Date(torrent.uploadTime).toLocaleString()}</td>
                                <td>{torrent.category}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </>
                  ) : (
                    <p>暂无上传记录</p>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {followModal.isOpen && (
        <div className="modal-overlay">
          <div className="modal-content follow-modal">
            <div className="modal-header">
              <h2>{followModal.type === "following" ? "关注列表" : "粉丝列表"}</h2>
              <button className="close-button" onClick={handleCloseFollowModal}>
                ×
              </button>
            </div>

            <div className="follow-modal-content">
              {followModal.loading ? (
                <div className="loading-state">加载中...</div>
              ) : followModal.list.length > 0 ? (
                <div className="follow-list">
                  {followModal.list.map((user) => (
                    <div key={user.userId} className="follow-item">
                      <div className="follow-user-info">
                        <img
                          src={user.avatarUrl || "/default_avatar.jpg"}
                          alt="用户头像"
                          className="follow-avatar"
                          onError={(e) => {
                            e.target.src = "/default_avatar.jpg"
                          }}
                        />
                        <div className="follow-user-details">
                          <span className="follow-username">{user.nickname}</span>
                          <span className="follow-user-level">等级: {user.level}级</span>
                          <span className="follow-user-points">积分: {user.userPoints}</span>
                        </div>
                      </div>
                      <button
                        className="follow-action-button"
                        onClick={() => (window.location.href = `/otherProfile/${user.userId}`)}
                      >
                        查看资料
                      </button>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="empty-follow-state">
                  <p>{followModal.type === "following" ? "还没有关注任何人" : "还没有粉丝"}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default OtherProfile
